// pages/login/login.js
import * as echarts from '../ec-canvas/echarts';
const app = getApp();
function pieSet(chart, data) {
  var option = {
    title: {
      show: true,
      text: data + '%',
      x: 'center',
      y: 'center',
      iosDialog2: false,
      textStyle: {
        fontSize: '15',
        color: 'black',
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: "{d}%",
      show: false
    },
    legend: {
      orient: 'vertical',
      x: 'left',
      show: false
    },
    series:
    {
      name: '',
      type: 'pie',
      radius: ['65%', '85%'],
      avoidLabelOverlap: true,
      hoverAnimation: false,
      label: {
        normal: {
          show: false,
          position: 'center'
        },
        emphasis: {
          show: false
        }
      },
      labelLine: {
        normal: {
          show: false
        }
      },
      data: [
        { value: data, name: '' },
        { value: 100 - data, name: '' }
      ]
    }

  }
  chart.setOption(option);
  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    message: [],
    code: [],
    workoder: [],
    mvctHour: "",
    mesobj:{},
    operationRate: "",
    TxHour: "",
    healthData: 0,
    status: "",
    contractStatus: "",
    waringstatus: "",
    ec: {
      lazyLoad: true
    },
    usermessage: [],
    usercode: [],
    userworkoder: [],
    usermvctHour: "",
    userTxHour: "",
    userstatus: "",
    usercontractStatus: "",
    userwaringstatus: "",
    tomo: {
      value1: 0,
      value2: 0,
      value3: 0,
    },
    cybe: {
      value1: 0,
      value2: 0,
      value3: 0,
    },
    radi: {
      value1: 0,
      value2: 0,
      value3: 0,
    },
    equipCount: 0,
    repairCount: 0,
    juge: false,
    // 涉及到权限的模块
    list: [
      {
        pagePath: "/pages/main/index",
        iconPath: "/tabimage/index.png",
        selectedIconPath: "/tabimage/index_select.png",
        power: "main",
        text: "主页"
      }, {
        pagePath: "/pages/manage/manage",
        iconPath: "/tabimage/manage.png",
        selectedIconPath: "/tabimage/manage_select.png",
        power: "2zhgl",
        text: "智慧管理"
      },
      {
        pagePath: "/pages/qualityControl/index",
        iconPath: "/tabimage/qc.png",
        selectedIconPath: "/tabimage/qc_select.png",
        power: "3zhzk",
        text: "质控管理"
      },
      {
        pagePath: "/pages/waring/index",
        iconPath: "/tabimage/waring.png",
        selectedIconPath: "/tabimage/waring_select.png",
        power: "4znyj",
        text: "智能预警"
      },
      {
        pagePath: "/pages/person/index",
        iconPath: "/tabimage/my.png",
        selectedIconPath: "/tabimage/my_select.png",
        power: "allHave",
        text: "我的"
      }
    ],
    mainlist:[ {
      text: "设备概况",
      path: "equipment",
      power: "2zhgl_sbgk",
      icon: "/assets/manage/img/sbgk.png"
    },
    {
      text: "一键报修",
      path: "submit",
      power: "2zhgl_yjbx",
      icon: "/assets/manage/img/yjbx.png"
    },
    {
      text: "报修管理",
      path: "workLog",
      power: "2zhgl_gdgl",
      icon: "/assets/manage/img/bxgl.png"
    },
    {
      text: "备件管理",
      path: "spare",
      power: "2zhgl_bjsmzq",
      icon: "/assets/manage/spare.png"
    },
    {
      text: "健康管理",
      path: "healthManage",
      power: "6jkgl",
      icon: "/assets/manage/img/jkgl.png"
    },
    {
      text: "智能预警",
      path: "waring",
      power: "4znyj",
      icon: "/assets/manage/img/znyj.png"
    },
  ],
  mainlisttwo:[
    {
      text: "设备概况",
      path: "equipment",
      power: "2zhgl_sbgk",
      icon: "/assets/manage/img/sbgk.png"
    },
    {
      text: "一键报修",
      path: "submit",
      power: "2zhgl_yjbx",
      icon: "/assets/manage/img/yjbx.png"
    },
    {
      text: "报修管理",
      path: "workLog",
      power: "2zhgl_gdgl",
      icon: "/assets/manage/img/bxgl.png"
    },
    {
      text: "备件管理",
      path: "spare",
      power: "2zhgl_bjsmzq",
      icon: "/assets/manage/spare.png"
    },
    {
      text: "质控管理",
      path: "qualityControl",
      power: "3zhzk",
      icon: "/assets/manage/img/zkgl.png"
    },
    {
      text: "智能预警",
      path: "waring",
      power: "4znyj",
      icon: "/assets/manage/img/znyj.png"
    }
  ],
  powerItem:[]
  },
  close: function () {
    let self = this
    this.axios.update("Message", {id:self.data.mesobj.id,status:1}).then((res) => {
      if (res.code == '200') {
        wx.showToast({
          title: '消息已读',
          icon: 'success',
          duration: 2000,
          success: () => {
            this.setData({
              iosDialog2: false,
          })
          self.getRightData()
          }
        })
      } else {

      }
    })

},
  // 初始化饼图
  initPieChart(rate) {
    this.RingDom = this.selectComponent('#mychart-dom-pie');
    this.RingDom.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      canvas.setChart(chart);
      pieSet(chart, rate)
      this.chart = chart;
      return chart;
    });
  },
  toPage(e) {
    let path = e.currentTarget.dataset.path;
    if(path=='waring'){
      this.warning()
    }else if(path=='qualityControl'){
      wx.switchTab({
        url: '../qualityControl/index',
      })
    }
      else{
      this.Router.push(path);
      console.log(e, '权限')
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let token = this.Store.getItem('token');
    if (!token) {
      this.Router.push({
        path: "login",
        query: { test: 111 },
        openType: 'reLaunch',
      })
    }
    let item=[]
    if (this.Store.getItem("identity") == "内部员工") {
      this.setData({
        juge: true
      })
      item = this.data.mainlist
    } else {
      this.setData({
        juge: false
      })
      item = this.data.mainlisttwo
    }
    
    let temp =this.powerJuge(item)
    this.setData({
      powerItem:temp
    })
    this.getRightDatatwo()
    this.getRightData()
    this.equipmentInit()
  },
  // 页面权限
  powerJuge(arr) {
    let powerItem = wx.getStorageSync('power');
    //powerItem = ',' + powerItem + ',';
    let temp = arr.filter((item) => {
      let power =  item.power ;
      //let power = ',' + item.power + ',';
      if (powerItem.indexOf(power) > -1) {
        return item
      }
    })
    console.log(temp)
    return temp
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },
  swiperChange(e) {

    let index = e.detail.current
    this.getAllData(this.data.code[index])
  },

  // 点击进入设备概况
  toEquip() {
    this.Router.push('equipment')
  },
  // 点击进入一键报修
  toRepair() {
    this.Router.push('submit')
  },
  // 点击进入报修管理
  toWorkOrder() {
    this.Router.push('workLog')
  },
  // 点击进入备件管理
  toSpare() {
    this.Router.push('spare')
  },
  userhome() {
    this.Router.push("healthManage")
  },
  /**
   * 生命周期函数--监听页面显示
   */
  powerJuge(arr) {
    let powerItem = wx.getStorageSync('power');
    //powerItem = ',' + powerItem + ',';
    let temp = arr.filter((item) => {
      let power = item.power;
      //let power = ',' + item.power + ',';
      if (powerItem.indexOf(power) > -1) {
        return item
      }
      if (power == 'allHave') {
        return item
      }
    })
    console.log(temp)
    return temp
  },
  onShow: function () {
    let { list } = this.data
    let itemMenu = this.powerJuge(list)
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {

      let index = itemMenu.findIndex((item) => {
        if (item.power == 'main') {
          return true
        }
      })
      console.log(index, '索引', itemMenu)
      this.getTabBar().setData({
        itemMenu,
        selected: index,
      })
    }
    this.getRightDatatwo()
    this.getRightData()
  },
  //设备号初始化
  equipmentInit() {
    let self = this;
    this.axios.custom("AllInstalledProducts", "serialOrLotNumbers", {
      id: self.Store.getItem("userid"),
    })
      .then(function (response) {

        self.getAllData(response.data[0])
        self.setData({
          code: response.data
        })
      });
  },
  toShebei() {
    this.Router.push("equipment")
  },
  warning() {
    wx.switchTab({
      url: '../waring/index',
    })
  },
  toBaoxiu() {
    this.Router.push("workLog")
  },
  //消息通知
  getRightData() {

    let self = this
    this.axios.custom("MainPage", "getMainPageMessage", { customerId: this.Store.getItem("customerId"), typeName: this.Store.getItem("identity") })
      .then(function (response) {

        if (response.data.messages != undefined&&response.data.messages.length>0) {
          let arr = []
          arr = response.data.messages
          arr.forEach(e => {
            if (e.content.length > 30) {
              e.text = e.content.substring(0, 30)
            } else {
              e.text = e.content
            }
          })
          if(response.data.messages.length>3){
             self.setData({
            message: arr.splice(0,3)
          }) 
          }else{
            self.setData({
              message: arr
            })
          }
        }else{
          let obj = [{
            text:'暂无消息通知'
          }]
          self.setData({
            message: obj
          })
        }
      });
  },
  infor(e){
console.log(e)
console.log(e)
  let obj = e.currentTarget.dataset.item
    this.setData({
      iosDialog2:true,
      mesobj:obj
    })
  },
  //消息通知
  getRightDatatwo() {

    let self = this
    this.axios.custom("MainPage", "getMainPageMessage", { customerId: this.Store.getItem("customerId"), typeName: this.Store.getItem("identity") })
      .then(function (response) {

        if (response.data.messages != undefined&&response.data.messages.length>0) {

          let arr = []
          arr = response.data.messages
          arr.forEach(e => {
            if (e.content.length > 30) {
              e.text = e.content.substring(0, 30)
            } else {
              e.text = e.content
            }
          })
          if(response.data.messages.length>3){
            self.setData({
              usermessage: arr.splice(0,3)
            })
          }else{
            self.setData({
              usermessage: arr
            })
          }

        }else{
          let obj = [{
            text:'暂无消息通知'
          }]
          self.setData({
            usermessage: obj
          })
        }
      });
    this.axios.custom("MainPage", "getMainPageInfo", {})
      .then(function (res) {

        if (
          res.data != undefined &&
          res.data.equipmentWorkOrder.length > 0
        ) {
          res.data.equipmentWorkOrder.forEach((e) => {
            if (e.type == "TOMO") {
              self.data.tomo.value1 = e.notBegin;
              self.data.tomo.value2 = e.running;
              self.data.tomo.value3 = e.completed;
              self.setData({
                tomo: self.data.tomo
              })
            }
            if (e.type == "Radixact") {
              self.data.radi.value1 = e.notBegin;
              self.data.radi.value2 = e.running;
              self.data.radi.value3 = e.completed;
              self.setData({
                radi: self.data.radi
              })
            }
            if (e.type == "CK") {
              self.data.cybe.value1 = e.notBegin;
              self.data.cybe.value2 = e.running;
              self.data.cybe.value3 = e.completed;
              self.setData({
                cybe: self.data.cybe
              })
            }
          });
        }
        if (res.data != undefined) {
          self.setData({
            equipCount: res.data.equipmentCountViewModel.equipCount,
            repairCount: res.data.equipmentCountViewModel.repairCount
          })
        }


      });
  },

  //获取主页数据
  getAllData(code) {

    let self = this;
    this.axios.custom("MainPage", "getMainPageEquipment", { id: code })
      .then(function (response) {
          let arr = response.data.allOpenWorkOrders
          arr.forEach(e=>{
            e.createdDateOrTime = e.createdDateOrTime.substring(0,e.createdDateOrTime.length-9)
          })
          
        self.setData({
          workoder: arr,
          status: response.data.allInstalledProducts.status ? response.data.allInstalledProducts.status : "",
          contractStatus: response.data.allInstalledProducts.contractStatus ? response.data.allInstalledProducts.contractStatus : "",
          operationRate: response.data.operationRate ? response.data.operationRate : 0
        })
        if (!self.data.juge) {
          self.initPieChart(response.data.operationRate)
        }

      });
    this.axios.custom("MainPage", "getMainPageEquipmentLog", { id: code })
      .then((response) => {

        if (response.data.beamOnHourSum) {
          self.setData({
            mvctHour: response.data.beamOnHourSum.imageOn ? response.data.beamOnHourSum.imageOn : 0,
            TxHour: response.data.beamOnHourSum.treatmentOn ? response.data.beamOnHourSum.treatmentOn : 0,
            waringstatus: response.data.warningStatus ? response.data.warningStatus : ""
          })
        } else {
          self.setData({
            mvctHour: 0,
            TxHour: 0,
            waringstatus: ""
          })
        }
      });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
